<?php

class E_UnitOfWork
{
	private	$loadMap;
	protected $insertList;
	protected $updateList;
	protected $deleteList;
	private static  $instance = null;
	protected $_DB = null;
	private  function __construct()
	{
		$this->loadMap = array();
		$this->insertList = array();
		$this->updateList = array();
		$this->deleteList = array();
	}
	public static function getWork()
	{
		if(self::$instance == null)
			self::$instance = new self();
		return self::$instance;
	}
	public function register($entity)
	{
		$this->loadMap[$entity->getEntityKey()] = $entity;
	}

	public function hasEntity($key)
	{
		return array_key_exists($key, (array)$this->loadMap) ;
	}
	public function getEntity($key)
	{
		if(array_key_exists($key, (array)$this->loadMap))
		{
			$entity = $this->loadMap[$key];
		}
		return $entity;
	}
	
	public function makeTreeList()
	{
		$this->updateList = array();
		$this->insertList = array();
		$this->_DB = E_DBConnectionPool::getDbHandle(1);
		if(!empty($this->loadMap))
		foreach ($this->loadMap as $entity)
		{
			if($entity->getUpdateSql())
			{
//				$sql = "select version from {$entity->getTableName()} where {$entity->table['id']} = $entity->id";
//				$row = $this->_DB->fetch($sql);
//				if($row['version'] > $entity->version)
//				{ throw new Exception("version!");}			
				$this->updateList[] = $entity->getUpdateSql();
				$entity->_updatestack = array();
			}
		}
		if(!empty($this->loadMap))
		foreach ($this->loadMap as $entity)
		{
			
			if($entity->getInsertSql())
			$this->insertList[] = $entity->getInsertSql();
			$entity->_isinsert = false;
		}
		
		if(!empty($this->loadMap))
		foreach ($this->loadMap as $entity)
		{
			if($entity->isDelete())
			$this->deleteList[] = $entity->getDeleteSql();
			$entity->deletestack = 0;
		}
		
		
	}
	public function commit()
	{	
		
		$this->makeTreeList();
		foreach($this->insertList as $insert)
		{
			$this->_DB->query($insert);
		}
		foreach($this->updateList as $update)
		{
			$query = $this->_DB->query($update);
			$num = $this->_DB->get_num();
			if($num <= 0)
			{ throw new Exception("version!");}		
		}
		foreach($this->deleteList as $delete)
		{
			$this->_DB->query($delete);
		}
	}
}
?>